package api;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import domain.Product;
import service.ProductService;
import utils.GetRequestJsonUtils;
import utils.Response;
import utils.ResponseCode;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

public class GetBooksServlet extends HttpServlet {
    //该请求可以携带参数:分类查询，还可以查看分页参数，也课题什么都不携带，就算是查询所有书籍
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        JSONObject paramsObjeck= GetRequestJsonUtils.getRequestJsonObject(req);
        JSONObject object=null;
        String category=null;
        Response build=null;
        //参数格式{category:"",pageSize:10,pageIndex:3}
        if (paramsObjeck!=null) {
            if (paramsObjeck.containsKey("category")) {
                String categroy = paramsObjeck.getString("category");
            }
            if (paramsObjeck.containsKey("pageSize")) {
                int pageSize = paramsObjeck.getInteger("pageSize");
            }
            if (paramsObjeck.containsKey("pageIndex")) {
                int pageIndex = paramsObjeck.getInteger("pageIndex");
            }
        }
        ProductService service=new ProductService();

        if (paramsObjeck==null){
            try {

                List<Product> books = service.getAllproducts();
                build=Response.build(ResponseCode.SUCCESS,books);
            }catch (SQLException e){
                e.printStackTrace();
                build=Response.build(ResponseCode.ERROR_DB);
            }
        }else {
            build=Response.build(ResponseCode.ERROR);
        }
        resp.setContentType("application/json;charset=utf-8");
        resp.getWriter().write(JSON.toJSON(build).toString());
    }
}
